package com.polukeuro.app.utils;

import java.util.Map;

import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;

public class StringUtils {

	private static String substituteRe = "\\{([^\\s\\:\\}]+)(?:\\:([^\\s\\:\\}]+))?\\}";

	private static final RegExp pattern = RegExp.compile(substituteRe, "g");

	/**
	 * transform a string that contains variables with the value of these
	 * variables
	 * 
	 * @param template
	 *            the template that contains variables
	 * @param data
	 *            can be either a Map<String, String>, a JSONObject or an Object
	 * @return the transformed string
	 */
	public static String substitute(String template, Map<String, String> data) {
		String myTemplate = template;
		for (MatchResult m = pattern.exec(template); m != null; m = pattern.exec(template)) {
			String key = m.getGroup(0);
			String mapKey = m.getGroup(1);
			if(data.containsKey(mapKey)) {
				myTemplate = myTemplate.replace(key, data.get(mapKey));
			}
		}
		return myTemplate;
	}

}
